package com.moliku.insurance.process.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moliku.insurance.common.constant.CacheConsts;
import com.moliku.insurance.common.constant.CompanyEnum;
import com.moliku.insurance.common.constant.PolicyConfigKeyEnum;
import com.moliku.insurance.model.entity.Config;
import com.moliku.insurance.process.mapper.ConfigMapper;
import com.moliku.insurance.process.service.ConfigService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 配置服务
 *
 * @author Mr.Liu
 * @since 2021/3/29
 */
@Slf4j
@Service
@AllArgsConstructor
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements ConfigService {
    private final RedisTemplate<String, String> redisTemplate;

    private final ConfigMapper configMapper;

    @Override
    public String getConfigValue(final CompanyEnum company, final String hashKey) {
        log.info("========= 开始查询保险公司配置 =========");
        log.info("保险公司名称：【{}】", company.getName());
        log.info("保险公司编码：【{}】", company.getCode());
        log.info("查询的键名称：【{}】", hashKey);
        final String key = CacheConsts.POLICY_CONFIG + company.getCode();
        log.info("Redis key:【{}】", key);
        log.info("Redis hashKey:【{}】", hashKey);
        Object redisData = redisTemplate.opsForHash().get(key, hashKey);
        String result;
        if (redisData != null) {
            log.info("Redis命中,值：【{}】", redisData);
            result = String.valueOf(redisData);
        } else {
            log.info("Redis未命中,查询数据库");
            result = configMapper.getValue(company.getCode(), hashKey);
            if (StringUtils.isNotBlank(result)) {
                log.info("保存结果至Redis。key=【{}】，hashKey=【{}】,value=【{}】", key, hashKey, result);
                redisTemplate.opsForHash().put(key, hashKey, result);
            }
        }
        log.info("========= 查询保险公司配置结束，结果：【{}】 =========\n", StringUtils.isNotBlank(result) ? result : "空");
        return result;
    }

    @Override
    public String getConfigValue(CompanyEnum company, PolicyConfigKeyEnum configKey) {
        return getConfigValue(company, configKey.getKey());
    }
}
